package heap

import (
	"database/sql"
	"fmt"
	"game/readygo/quickstart/service"
	"game/readygo/timing"
	"game/readygo/util"
	"reflect"
)

// 具有可每日、每周、每月重置特点的实体服务
type IPlayerOneToOneResetableService[T IPlayerOneToOneEntity] interface {
	IPlayerOneToOneService[T]

	DoDailyReset(entity T)   //处理每日重置的函数
	DoWeeklyReset(entity T)  //处理每周重置的函数
	DoMonthlyReset(entity T) //处理每月重置的函数
}

type PlayerOneToOneResetableService[T IPlayerOneToOneEntity] struct {
	PlayerOneToOneService[T]
	iiService IPlayerOneToOneResetableService[T]
}

func (t *PlayerOneToOneResetableService[T]) InitRepository(db *sql.DB, service IPlayerOneToOneResetableService[T], entityTemplate T) {
	t.PlayerOneToOneService.InitRepository(db, service, entityTemplate)
	t.iiService = service
}

var dailyType reflect.Type = reflect.TypeOf((*service.DailyResetEntity)(nil)).Elem()
var weeklyType reflect.Type = reflect.TypeOf((*service.WeeklyResetEntity)(nil)).Elem()
var monthlyType reflect.Type = reflect.TypeOf((*service.MonthlyResetEntity)(nil)).Elem()

func (t *PlayerOneToOneResetableService[T]) GetEntity(playerId int64) T {
	entity := t.PlayerOneToOneService.GetEntity(playerId)
	rType := reflect.TypeOf(entity)
	needUpdate := false
	now := util.Now()
	if rType.Implements(dailyType) {
		dailyEntity := reflect.ValueOf(entity).Interface().(service.DailyResetEntity)
		if now >= dailyEntity.GetDailyTime() {

			dailyEntity.SetDailyTime(t.dailyResetTime())
			t.iiService.DoDailyReset(entity)
			needUpdate = true
		}
	}
	if rType.Implements(weeklyType) {
		weeklyEntity := reflect.ValueOf(entity).Interface().(service.WeeklyResetEntity)
		if now >= weeklyEntity.GetWeeklyTime() {
			weeklyEntity.SetWeeklyTime(t.weeklyResetTime())
			t.iiService.DoWeeklyReset(entity)
			needUpdate = true
		}
	}
	if rType.Implements(monthlyType) {
		monthlyEntity := reflect.ValueOf(entity).Interface().(service.MonthlyResetEntity)
		if now >= monthlyEntity.GetMonthlyTime() {
			monthlyEntity.SetMonthlyTime(t.monthlyResetTime())
			t.iiService.DoMonthlyReset(entity)
			needUpdate = true
		}
	}
	if needUpdate {
		t.Update(entity)
	}
	return entity
}

func (t *PlayerOneToOneResetableService[T]) DoDailyReset(entity T) {
	fmt.Println("DoDailyReset In PlayerOneToOneResetableService")
}
func (t *PlayerOneToOneResetableService[T]) DoWeeklyReset(entity T) {
	fmt.Println("DoWeeklyReset In PlayerOneToOneResetableService")
}
func (t *PlayerOneToOneResetableService[T]) DoMonthlyReset(entity T) {
	fmt.Println("DoMonthlyReset In PlayerOneToOneResetableService")
}

func (t *PlayerOneToOneResetableService[T]) dailyResetTime() int64 {
	return timing.NextDayOTime()
}

func (t *PlayerOneToOneResetableService[T]) weeklyResetTime() int64 {
	return timing.NextWeekMondayOTime()
}

func (t *PlayerOneToOneResetableService[T]) monthlyResetTime() int64 {
	return timing.NextMonthOTime()
}
